package com.jr.controller;

import com.jr.pojo.Order;
import com.jr.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/order")
@CrossOrigin(origins = "*")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @PostMapping("/create")
    public boolean createOrder(@RequestBody Order order) {
        System.out.println("创建订单");
        return orderService.createOrder(order);
    }

    @GetMapping("/list")
    public Map<String, Object> getOrdersByUserId(@RequestParam Integer userId, @RequestParam(required = false) String userType, 
                                                @RequestParam(defaultValue = "1") Integer pageIndex, 
                                                @RequestParam(defaultValue = "5") Integer pageSize,
                                                @RequestParam(required = false) String status) {
        System.out.println("查询订单列表 - userId: " + userId + ", userType: " + userType + ", pageIndex: " + pageIndex + ", pageSize: " + pageSize + ", status: " + status);
        
        int totalCount = orderService.getOrderCount(userId, userType, status);
        int pageCount = totalCount % pageSize == 0 ? totalCount / pageSize : (totalCount / pageSize) + 1;
        
        ArrayList<Order> orders = orderService.getOrdersByPage(userId, userType, pageIndex, pageSize, status);
        System.out.println("查询到的订单数量: " + orders.size());
        for (Order order : orders) {
            System.out.println("订单信息: " + order.toString());
        }
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("orders", orders);
        map.put("pageCount", pageCount);
        map.put("totalCount", totalCount);
        map.put("currentPage", pageIndex);
        map.put("pageSize", pageSize);
        map.put("statusFilter", status);
        System.out.println("返回的订单数据: " + map);
        return map;
    }

    @GetMapping("/detail")
    public Order getOrderById(@RequestParam Integer orderId) {
        System.out.println("查询订单详情");
        return orderService.getOrderById(orderId);
    }

    @PutMapping("/updateStatus")
    public Map<String, Object> updateOrderStatus(@RequestParam Integer orderId, @RequestParam String status) {
        System.out.println("更新订单状态 - orderId: " + orderId + ", status: " + status);
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 验证参数
            if (orderId == null || orderId <= 0) {
                result.put("success", false);
                result.put("message", "订单ID无效");
                return result;
            }
            
            if (status == null || status.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "状态不能为空");
                return result;
            }
            
            // 验证状态值是否有效
            String[] validStatuses = {"pending", "confirmed", "in_progress", "completed", "cancelled"};
            boolean isValidStatus = false;
            for (String validStatus : validStatuses) {
                if (validStatus.equals(status)) {
                    isValidStatus = true;
                    break;
                }
            }
            
            if (!isValidStatus) {
                result.put("success", false);
                result.put("message", "无效的状态值: " + status);
                return result;
            }
            
            // 执行更新
            boolean updateResult = orderService.updateOrderStatus(orderId, status);
            
            if (updateResult) {
                result.put("success", true);
                result.put("message", "状态更新成功");
                System.out.println("订单状态更新成功 - orderId: " + orderId + ", newStatus: " + status);
            } else {
                result.put("success", false);
                result.put("message", "状态更新失败，可能是订单不存在");
                System.out.println("订单状态更新失败 - orderId: " + orderId + ", status: " + status);
            }
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "状态更新异常: " + e.getMessage());
            System.out.println("订单状态更新异常 - orderId: " + orderId + ", status: " + status + ", error: " + e.getMessage());
            e.printStackTrace();
        }
        
        return result;
    }
    
    @GetMapping("/test")
    public Map<String, Object> testOrderAPI(@RequestParam Integer userId) {
        System.out.println("测试订单API - userId: " + userId);
        Map<String, Object> result = new HashMap<>();
        try {
            ArrayList<Order> orders = orderService.getOrdersByUserId(userId, "pet_owner");
            result.put("success", true);
            result.put("message", "查询成功");
            result.put("userId", userId);
            result.put("orderCount", orders.size());
            result.put("orders", orders);
            System.out.println("测试查询结果 - 订单数量: " + orders.size());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询失败: " + e.getMessage());
            result.put("error", e.getClass().getSimpleName());
            System.out.println("测试查询失败: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
